package pl.matt.main;

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.media.jai.PlanarImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.springframework.context.ApplicationContext;

import pl.matt.dao.FrameRegionDao;
import pl.matt.media.utils.ImageUtils;
import pl.matt.model.FrameRegion;
import pl.matt.swing.IntTextField;
import pl.matt.utils.ApplicationContextUtils;

/**
 * @author mateusz
 *
 */
public class FrameRegionViever {
	
	private IntTextField idField;
	private JLabel imageLabel;
	private ApplicationContext applicationContext;
	
	public FrameRegionViever() {
		applicationContext = ApplicationContextUtils.getApplicationContest();
		
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel mainPanel = new JPanel();
		JPanel topPanel = new JPanel();
		
		idField = new IntTextField(0, 10);
		imageLabel = new JLabel();
		JButton showButton = new JButton("show");
		showButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				displayAndMove(0);
			}
		});
		
		JButton prevButton = new JButton("previous");
		prevButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				displayAndMove(-1);
			}
		});
		
		JButton nextButton = new JButton("next");
		nextButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				displayAndMove(1);
			}
		});
		
		mainPanel.setLayout(new BorderLayout());
		topPanel.add(idField);
		topPanel.add(showButton);
		topPanel.add(prevButton);
		topPanel.add(nextButton);
		mainPanel.add(topPanel, BorderLayout.NORTH);
		mainPanel.add(imageLabel, BorderLayout.CENTER);
		frame.setContentPane(mainPanel);
		
		frame.setSize(400, 400);
		frame.setVisible(true);
		
	}

	public static void main(String[] args) {
		new FrameRegionViever();
	}
	
	private void displayAndMove(int offset) {
		int value = idField.getValue() + offset;
		idField.setText("" + value);
		displayRegion(value);
	}
	
	private void displayRegion(int regionId) {
		FrameRegionDao frameRegionDao = (FrameRegionDao) applicationContext.getBean("frameRegionDao");
		FrameRegion frameRegion = frameRegionDao.read((long)idField.getValue());
		String path = frameRegion.getFrame().getFilePath();
		PlanarImage pi = ImageUtils.readImage(path);
		Image source = pi.getAsBufferedImage();
		Image image = ImageUtils.cropImage(source, frameRegion.getX(), frameRegion.getY(), frameRegion.getWidth(), frameRegion.getHeight());
		imageLabel.setIcon(new ImageIcon(image));
	}
	
}
